package com.yunkazaixian.syntelecom.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunkazaixian.syntelecom.entity.*;
import com.yunkazaixian.syntelecom.mapper.Mc31gpsMapper;
import com.yunkazaixian.syntelecom.mapper.McProductNormsMapper;
import com.yunkazaixian.syntelecom.mapper.McSimDxMapper;
import com.yunkazaixian.syntelecom.mapper.SysDeptMapper;
import com.yunkazaixian.syntelecom.service.DXService;
import com.yunkazaixian.syntelecom.service.IMcSimDxService;
import com.yunkazaixian.syntelecom.utils.ListUtils;
import com.yunkazaixian.syntelecom.utils.NettyClient;
import com.yunkazaixian.syntelecom.utils.R;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 手机卡 服务实现类
 * </p>
 *
 * @author Lin
 * @since 2024-03-21
 */
@Service
public class McSimDxServiceImpl extends ServiceImpl<McSimDxMapper, McSimDx> implements IMcSimDxService {
    @Autowired
    McProductNormsMapper normsMapper;

    @Autowired
    McSimDxMapper simDxMapper;

    @Autowired
    DXService dxService;

    @Autowired
    SysDeptMapper deptMapper;

    @Autowired
    NettyClient nettyClient;

    @Autowired
    Mc31gpsMapper gpsMapper;


    public Long[] getTransAgentIds() {
        LambdaQueryWrapper<Mc31gps> wrapper=new LambdaQueryWrapper<>();
        wrapper.ne(Mc31gps::getDelFlag,"0");
        List<Long> collect = gpsMapper.selectList(wrapper).stream().map(it -> it.getDeptId()).collect(Collectors.toList());
        return collect.toArray(new Long[0]);
    }

    /**
     * @param date "20240305"
     * @return
     */
    @RequestMapping("/pushAllByDay")
    @ResponseBody
    public Object pushAllByDay(String date) {

        List<SysDept> agentList = getAllAgentFromId(getTransAgentIds());
        Long[] ids = agentList.stream().map(i -> i.getDeptId()).collect(Collectors.toList()).toArray(new Long[0]);
        LambdaQueryWrapper lambda = new LambdaQueryWrapper<McSimDx>().in(McSimDx::getAgentId, ids)
                .isNotNull(McSimDx::getPackageId)
                .ne(McSimDx::getPackageId,"");

        List<McSimDx> simList = simDxMapper.selectList(lambda);
        for (McSimDx simDx : simList) {
            pushDay(simDx, date);
        }

        return R.ok();

    }


    /**
     * 测试
     * month"202403"
     *
     * @return
     */
    @RequestMapping("/pushAllByMonth")
    @ResponseBody
    public Object pushAllByMonth(String month) {

        List<SysDept> agentList = getAllAgentFromId(getTransAgentIds());
        Long[] ids = agentList.stream().map(i -> i.getDeptId()).collect(Collectors.toList()).toArray(new Long[0]);
        LambdaQueryWrapper lambda = new LambdaQueryWrapper<McSimDx>().in(McSimDx::getAgentId, ids)
                .isNotNull(McSimDx::getPackageId)
                .ne(McSimDx::getPackageId,"");
        List<McSimDx> simList = simDxMapper.selectList(lambda);
        for (McSimDx simDx : simList) {
            pushMonth(simDx, month);
        }
        return R.ok();

    }


    private Object pushDay(McSimDx simDx, String date) {
        Object o = getDayBean(simDx, date);
        nettyClient.push(o);
        return o;
    }


    private Object pushMonth(McSimDx simDx, String month) {
        Object o = getMonthBean(simDx, month);
        nettyClient.push(o);
        return o;
    }


    /**
     * date
     *
     * @param sim
     * @param date 2023
     * @return
     */
    private DayReq getDayBean(McSimDx sim, String date) {
        DayReq dayReq = new DayReq();
        dayReq.setOperator("中国电信");
        dayReq.setIccid(sim.getIccid());
        dayReq.setRealSimCard(sim.getTelephone());
        dayReq.setType("day");
        dayReq.setTime(date.substring(0, 4) + "-" + date.substring(4, 6) + "-" + date.substring(6));
        List<McProductNorms> mcProductNorms = normsMapper.selectPackage(new LambdaQueryWrapper<McProductNorms>().eq(McProductNorms::getId, sim.getPackageId()));
        if (!ListUtils.isEmpty(mcProductNorms)) {
            McProductNorms norm = mcProductNorms.get(0);
            dayReq.setSetMeal(norm.getSkuName());
            Double packFlow = Double.parseDouble(norm.getFlow());
            System.out.println("每月" + packFlow + "MB");
            try {
                dayReq.setSurplus(toM2(packFlow - dxService.queryPakage(sim.getTelephone(), date.substring(0, 6) + "01")));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        try {
            dayReq.setTotalToday(toM2(dxService.queryTrafficByDate(sim.getTelephone(), date, date)));

        } catch (Exception e) {
            e.printStackTrace();
        }
        return dayReq;
    }

    /**
     * @param sim
     * @param month 20200801
     * @return
     */
    private MonthReq getMonthBean(McSimDx sim, String month) {
        MonthReq monthReq = new MonthReq();
        monthReq.setOperator("中国电信");
        monthReq.setIccid(sim.getIccid());
        monthReq.setRealSimCard(sim.getTelephone());
        monthReq.setType("month");
        List<McProductNorms> mcProductNorms = normsMapper.selectPackage(new LambdaQueryWrapper<McProductNorms>().eq(McProductNorms::getId, sim.getPackageId()));
        if (!ListUtils.isEmpty(mcProductNorms)) {
            McProductNorms norm = mcProductNorms.get(0);
            monthReq.setSetMeal(norm.getSkuName());
            try {
                monthReq.setTotalMonth(toM2(dxService.queryPakage(sim.getTelephone(), month + "01")));
            } catch (Exception e) {
                e.printStackTrace();
            }
            Double packFlow = Double.parseDouble(norm.getFlow());

            if (monthReq.getTotalMonth() > packFlow) {
                monthReq.setExcessQuantity(new BigDecimal(monthReq.getTotalMonth() - packFlow).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
            } else {
                monthReq.setExcessQuantity(0.);
            }
        }
        monthReq.setTime(month.substring(0, 4) + "-" + month.substring(4));
        return monthReq;
    }


    public Double toM2(String src) {
        return new BigDecimal(src.replaceAll("MB", ""))
                .setScale(2, BigDecimal.ROUND_HALF_UP)
                .doubleValue();
    }

    public Double toM2(Double src) {
        return new BigDecimal(src).setScale(2, BigDecimal.ROUND_HALF_UP)
                .doubleValue();
    }


    //获取所有代理,含自己
    public List<SysDept> getAllAgentFromId(Long... ids) {
        LambdaQueryWrapper<SysDept> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SysDept::getDeptId, ids);
        List<SysDept> listAgent = deptMapper.selectList(queryWrapper);
        if (listAgent == null) {
            listAgent = Lists.newArrayList();
        }
        listAgent.addAll(getAllDescendantsById(ids));

        return listAgent;
    }

    //获取所有子孙，不含自己
    private List<SysDept> getAllDescendantsById(Long... ids) {
        //根据父ID查询部门
        LambdaQueryWrapper<SysDept> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SysDept::getParentId, ids);
        List<SysDept> departments = deptMapper.selectList(queryWrapper);
        if (!ListUtils.isEmpty(departments)) {
            //拿到当前所有部门ID
            Long[] parentIds = departments.stream().map(SysDept::getDeptId).collect(Collectors.toList()).toArray(new Long[0]);
            //拼接子部门查询结果
            departments.addAll(getAllDescendantsById(parentIds));
            return departments;
        } else {
            //如果没有下级部门那么我们就返回空集合，结束递归。
            return Lists.newArrayList();
        }
    }

    @Override
    public Integer updateMcSimDx(McSimDx mcSimDx) {
        LambdaUpdateWrapper<McSimDx> lambdaUpdateWrapper = new LambdaUpdateWrapper<McSimDx>()
                .eq(McSimDx::getIccid, mcSimDx.getIccid());
        if(mcSimDx.getNetworkOutage() != null){
            lambdaUpdateWrapper.set(McSimDx::getNetworkOutage, mcSimDx.getNetworkOutage());
        }
        if(StringUtils.isNotBlank(mcSimDx.getCardboard())){
            lambdaUpdateWrapper.set(McSimDx::getCardboard, mcSimDx.getCardboard());
        }
        if(StringUtils.isNotBlank(mcSimDx.getActiveTime())){
            lambdaUpdateWrapper.set(McSimDx::getActiveTime, mcSimDx.getActiveTime());
        }
        if(StringUtils.isNotBlank(mcSimDx.getArriveTime())){
            lambdaUpdateWrapper.set(McSimDx::getArriveTime, mcSimDx.getArriveTime());
        }
        if(StringUtils.isNotBlank(mcSimDx.getIsOutThreshold())){
            lambdaUpdateWrapper.set(McSimDx::getIsOutThreshold, mcSimDx.getIsOutThreshold());
        }
        if(StringUtils.isNotBlank(mcSimDx.getImPayStatus())){
            lambdaUpdateWrapper.set(McSimDx::getImPayStatus, mcSimDx.getImPayStatus());
        }
        // 上线时间
        if(StringUtils.isNotBlank(mcSimDx.getImSaleProvince())){
            lambdaUpdateWrapper.set(McSimDx::getImSaleProvince, mcSimDx.getImSaleProvince());
        }
        // 下线时间
        if(StringUtils.isNotBlank(mcSimDx.getImSaleCity())){
            lambdaUpdateWrapper.set(McSimDx::getImSaleCity, mcSimDx.getImSaleCity());
        }
        lambdaUpdateWrapper.set(McSimDx::getUpdateTime, LocalDateTime.now());
        return simDxMapper.update(lambdaUpdateWrapper);
    }
}
